package com.two.screen.water.balance.net.api

import com.two.screen.water.balance.bean.IndexBean
import com.two.screen.water.balance.bean.LoginBean
import com.two.screen.water.balance.bean.ServerGoods
import com.two.screen.water.balance.bean.database.UserDB
import com.two.screen.water.balance.bean.database.UserDBDao
import com.two.screen.water.balance.listener.ApiCallBack
import com.two.screen.water.balance.listener.MyObserver
import com.two.screen.water.balance.ui.App
import com.two.screen.water.balance.ui.activity.base.BaseActivity
import com.two.screen.water.balance.utils.*
import io.reactivex.Observable
import io.reactivex.ObservableOnSubscribe
import java.util.*

object DBApi {
    var DEFAULT_ACCOUNT = "1001"
    var DEFAULT_PASSWORD = "1001"

    var mDefaultLogoList: MutableList<String> = mutableListOf(
        "https://img2.woyaogexing.com/2021/12/29/d97008d2f6444fc782125d1818f190e1!400x400.jpeg",
        "https://img2.woyaogexing.com/2021/12/29/4688e6a5f25a44a4bd5d182b8e06df1f!400x400.jpeg",
        "https://img2.woyaogexing.com/2021/12/29/fdec56b31e6744148c206e5c05fe7ada!400x400.jpeg",
        "https://img2.woyaogexing.com/2021/12/29/32b4c0c8b5674abd9cd3fb11cdd3e8dd!400x400.jpeg",
        "https://img2.woyaogexing.com/2021/12/29/502fe334c8f4442da6a21e0cc5fa3929!400x400.jpeg",
        "https://img2.woyaogexing.com/2021/12/29/2229c7bfd4524813a7eb46e3f2396aac!400x400.jpeg",
        "https://img2.woyaogexing.com/2021/12/29/264da94537794452bb0ecfeef2d26381!400x400.jpeg",
        "https://img2.woyaogexing.com/2021/12/29/da0058d34c2d45b2be8ea9ff511823b1!400x400.jpeg",
        "https://img2.woyaogexing.com/2021/12/29/9bfbccc64f464b01b528913278081c1c!400x400.jpg",
        "https://img2.woyaogexing.com/2021/12/29/5481ff4da17445c5ba1129242930d096!400x400.jpeg"
    )

    /*初始化首次帐号*/
    fun initLocalAccount(baseActivity: BaseActivity, apiCallBack: ApiCallBack? = null) {
        Observable.create(ObservableOnSubscribe<UserDB> { e ->
            var userDB = App.mDaoMaster?.newSession()
                ?.queryBuilder(UserDB::class.java)
                ?.where(UserDBDao.Properties.Accounts.eq(DEFAULT_ACCOUNT))
                ?.offset(0)?.limit(1)?.list()?.firstOrNull()
            d("DBApi:initLocalAccount:userList:${CommUtils.gson.toJson(userDB)}")
            if (userDB == null) {
                //一般首次登陆会触发。
                userDB = UserDB().apply {
                    this.id = DEFAULT_ACCOUNT.toLong()
                    this.userName = "收银员"
                    this.accounts = DEFAULT_ACCOUNT
                    this.createTime = System.currentTimeMillis() / 1000
                    this.createTimeName = CommUtils.toYMD_HMS(this.createTime)
                    this.logo = mDefaultLogoList[Random().nextInt(mDefaultLogoList.size)]
                    this.passwords = CommUtils.encodeByMD5(CommUtils.encodeByMD5(DEFAULT_PASSWORD))

                    this.token = "离线帐号"
                }
                App.mDaoMaster?.newSession()?.insertOrReplace(userDB)
            }
            //TODO:这里需要插入一些分类和菜品，然后在列表那里查出。
            //CateProductApi.initCateProductData()
//            val list = App.mDaoMaster?.newSession()?.queryBuilder(CateDB::class.java)
//                ?.list()
//            list?.forEach {
//                d("list:${CommUtils.gson.toJson(it.getProductDBList())}")
//            }
            e.onNext(userDB)
        })
            .compose(RxUtils.io())
            .compose(RxUtils.aLifecycle(baseActivity))
            .subscribe(object : MyObserver<UserDB>() {
                override fun onNext(t: UserDB) {
                }

                override fun onError(e: Throwable) {
                    ToastUtil.showToast(e.message.toString())
                }
            })
    }

    /*初始化首次帐号*/
    fun insertNewAccount(loginBean: LoginBean?, mTel: String, mPwd: String, baseActivity: BaseActivity, apiCallBack: ApiCallBack? = null) {
        if (loginBean == null) return
        Observable.create(ObservableOnSubscribe<UserDB> { e ->
            var userDB = App.mDaoMaster?.newSession()
                ?.queryBuilder(UserDB::class.java)
                ?.where(UserDBDao.Properties.Accounts.eq(mTel))
                ?.offset(0)?.limit(1)?.list()?.firstOrNull()
            d("DBApi:insertNewAccount:userList:${CommUtils.gson.toJson(userDB)}")
            if (userDB == null) {
                //一般首次登陆会触发。
                userDB = UserDB().apply {
                    this.id = loginBean.user_info?.id?.toLong() ?: 0L
                    this.userName = loginBean.user_info?.name.isNotAvailable()
                    this.userId = loginBean.user_info?.id
                    this.accounts = mTel
                    this.createTime = System.currentTimeMillis() / 1000
                    this.createTimeName = CommUtils.toYMD_HMS(this.createTime)
                    this.updateTime = this.createTime
                    this.updateTimeName = this.createTimeName
                    this.logo = loginBean.user_info?.header ?: mDefaultLogoList[Random().nextInt(mDefaultLogoList.size)]
                    this.passwords = CommUtils.encodeByMD5(CommUtils.encodeByMD5(mPwd))

                    this.token = loginBean.token
                    this.isWeight = loginBean.is_weight
                    this.userId = loginBean.user_info?.id
                    this.comId = loginBean.user_info?.com_id
                    this.status = loginBean.user_info?.status
                    this.circleId = loginBean.user_info?.circle_id
                    this.payButtonJson = try {
                        CommUtils.gson.toJson(loginBean.pay_button)
                    } catch (e: Exception) {
                        CommUtils.gson.toJson(mutableListOf(sortedMapOf("pay_id" to 1, "title" to "现金支付")))
                    }

                    //已交接
                    this.updateTime = System.currentTimeMillis() / 1000
                    this.updateTimeName = CommUtils.toYMD_HMS(this.updateTime)
                }
                App.mDaoMaster?.newSession()?.insertOrReplace(userDB)
            } else {
                //存在则更新密码
                userDB.apply {
                    this.userName = loginBean.user_info?.name?.isNotAvailable()
                    this.userId = loginBean.user_info?.id
                    this.logo = loginBean.user_info?.header ?: mDefaultLogoList[Random().nextInt(mDefaultLogoList.size)]
                    this.passwords = CommUtils.encodeByMD5(CommUtils.encodeByMD5(mPwd))

                    this.token = loginBean.token
                    this.isWeight = loginBean.is_weight
                    this.userId = loginBean.user_info?.id
                    this.comId = loginBean.user_info?.com_id
                    this.status = loginBean.user_info?.status
                    this.circleId = loginBean.user_info?.circle_id
                    this.payButtonJson = try {
                        CommUtils.gson.toJson(loginBean.pay_button)
                    } catch (e: Exception) {
                        CommUtils.gson.toJson(mutableListOf(sortedMapOf("pay_id" to 1, "title" to "现金支付")))
                    }

                    if (this.updateTime == null) {
                        //已交接
                        this.updateTime = System.currentTimeMillis() / 1000
                        this.updateTimeName = CommUtils.toYMD_HMS(this.updateTime)
                    }
                }
                App.mDaoMaster?.newSession()?.update(userDB)
            }



            e.onNext(userDB)
        })
            .compose(RxUtils.io())
            .compose(RxUtils.aLifecycle(baseActivity))
            .subscribe(object : MyObserver<UserDB>() {
                override fun onNext(t: UserDB) {
                }

                override fun onError(e: Throwable) {
                    ToastUtil.showToast(e.message.toString())
                }
            })
    }

    /*本地登陆*/
    fun getLogin(baseActivity: BaseActivity, mTel: String, mPwd: String, apiCallBack: ApiCallBack? = null) {
        var indexBean: IndexBean? = null
        var serverGoods: ServerGoods? = null
        Observable.create(ObservableOnSubscribe<UserDB> { e ->
//            App.mDaoSession?.UserDBDao?.delete(carInfoBean)
//            e.onNext(carInfoBean)
            d("pwd->$mPwd")
            val encodeByMD5 = CommUtils.encodeByMD5(CommUtils.encodeByMD5(mPwd))
            d("encodeByMD5->$encodeByMD5")
            val user = App.mDaoMaster?.newSession()?.queryBuilder(UserDB::class.java)
                ?.where(UserDBDao.Properties.Accounts.eq(mTel))
                ?.where(UserDBDao.Properties.Passwords.eq(encodeByMD5))
                ?.offset(0)?.limit(1)?.list()?.firstOrNull()
            if (user == null) e.onError(Throwable("帐号或密码输入不正确！")) else {
                val indexBeanJson = SPUtils.getString(Params.IndexBeanJson.plus("_").plus(DataApi.mUserId))
                val serverGoodsJson = SPUtils.getString(Params.ServerGoodsJson.plus("_").plus(DataApi.mUserId))
                indexBean = try {
                    CommUtils.gson.fromJson(indexBeanJson, IndexBean::class.java)
                } catch (e: Exception) {
                    null
                }
                serverGoods = try {
                    CommUtils.gson.fromJson(serverGoodsJson, ServerGoods::class.java)
                } catch (e: Exception) {
                    null
                }
                e.onNext(user)
            }
        })
            .compose(RxUtils.io())
            .compose(RxUtils.aLifecycle(baseActivity))
            .doOnSubscribe {
                baseActivity.mLoadingDialog.mTitle = "正在登陆..."
                baseActivity.mLoadingDialog.show()
            }
            .subscribe(object : MyObserver<UserDB>() {
                override fun onNext(t: UserDB) {
                    baseActivity.mLoadingDialog.dismiss()
                    apiCallBack?.success(t, indexBean, serverGoods)
                    //TODO:这里保存当前数据。
                }

                override fun onError(e: Throwable) {
                    ToastUtil.showToast(e.message.toString())
                    baseActivity.mLoadingDialog.dismiss()
                }
            })
    }

    private fun d(msg: String? = "null") {
        CommUtils.println("DBApi->", msg!!);
    }
}